package com.server.rule.loader.yml;

import com.server.exception.BusinessException;
import com.server.model.enums.ExceptionInfo;
import com.server.rule.loader.RuleReader;
import lombok.extern.slf4j.Slf4j;
import org.jeasy.rules.api.Rule;
import org.jeasy.rules.mvel.MVELRuleFactory;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Description: This is a sample class.
 * @Author Simon
 */
@Slf4j
public class YmlRuleReader implements RuleReader {

    MVELRuleFactory mvelRuleFactory;

    public void setMvelRuleFactory(MVELRuleFactory mvelRuleFactory){
        this.mvelRuleFactory=mvelRuleFactory;
    }

    public void checkMvelRuleFactory(){
        if (mvelRuleFactory==null){
            log.info("MvelRuleFactory未初始化");
            throw new BusinessException(ExceptionInfo.MVEL_RULE_FACTORY_LOAD_FAILED);
        }
    }

    // 停止使用
    @Deprecated
    @Override
    public Rule loadRuleByPath(String pathName) {
        checkMvelRuleFactory();
        Rule rule;
        try (FileReader fileReader = new FileReader(pathName)){
            rule = mvelRuleFactory.createRule(fileReader);
        } catch (Exception e) {
            throw new BusinessException(ExceptionInfo.RULE_READ_FAILED);
        }
        if (rule==null){
            log.info("规则文件读取失败");
            throw new BusinessException(ExceptionInfo.RULE_READ_FAILED);
        }
        return rule;
    }

    // todo 要加锁的考虑
    @Override
    public List<Rule> loadRulesByPath(String pathName) {

        checkMvelRuleFactory();

        List<Rule> ruleList=new ArrayList<>();
        File folder = new File(pathName);

        if (folder.isDirectory()) {
            File[] files = folder.listFiles(new FilenameFilter() {
                @Override
                public boolean accept(File dir, String name) {
                    return name.toLowerCase().endsWith(".yml") || name.toLowerCase().endsWith(".yaml");
                }
            });
            if (files != null) {
                for (File file : files) {
                    try (FileReader fileReader = new FileReader(file);) {
                        Rule rule = mvelRuleFactory.createRule(fileReader);
                        if (rule != null) {
                            ruleList.add(rule);
                        }
                    } catch (Exception e) {
                        // 处理文件读取或规则创建异常
                        log.error("Failed to load rule from file: " + file.getName(), e);
                    }
                }
            }
        }
        return ruleList;
    }
}
